package zencstudio.sgrealtor.view.phone;

import java.util.Arrays;

import zencstudio.sgrealtor.R;
import zencstudio.sgrealtor.adapter.CourseListAdapter;
import zencstudio.sgrealtor.model.Course;
import zencstudio.sgrealtor.model.ListCourse;
import zencstudio.sgrealtor.service.WireFrameServiceFactory;
import zencstudio.sgrealtor.utils.Const;
import zencstudio.sgrealtor.utils.WFErrorCode;
import zencstudio.sgrealtor.utils.WFUtils;
import zencstudio.sgrealtor.view.common.BaseActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

public class ListCourseActivity extends BaseActivity{

	private ListView lstCourse;
	private CourseListAdapter adapter;
	public void onCreate(Bundle saveInstance){
		super.onCreate(saveInstance);
		if(!WFUtils.checkInternetConnection(this)){
			showNetworkErrorDlg();
			finish();
			return;
		}
		TextView title = (TextView) findViewById(R.id.txtTitle);
		title.setText(getString(R.string.cource));
		lstCourse = (ListView) findViewById(R.id.lstCourse);
		adapter = new CourseListAdapter(this);
		setControls();
		loadData();
	}
	@Override
	protected void initUI() {
		setContentView(R.layout.course);
	}

	private void loadData(){
		showProgressDlg();
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				Message msg = handler.obtainMessage();
				ListCourse courses = null;
				try {
					courses = WireFrameServiceFactory.getInstance().getService().getCourses(0, 0);
				} catch (Exception e) {
					msg.arg1 = WFErrorCode.NETWORK_ERROR.getValue();
					e.printStackTrace();
				}
				
				msg.obj = courses;
				handler.sendMessage(msg);
			}
		});
		thread.start();
	}
	private Handler handler = new Handler(){
		public void handleMessage (Message msg){
			dismissProgressDlg();
			if(msg.arg1==WFErrorCode.NETWORK_ERROR.getValue()){
				showNetworkErrorDlg();
				return;
			}
			if(msg.obj!=null){
				ListCourse obj = (ListCourse) msg.obj;
				adapter.setListCourse(Arrays.asList(obj.getListCourse()));
				lstCourse.setAdapter(adapter);
			}
		}
	};
	private void setControls(){
		lstCourse.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Course course = (Course) adapter.getItem(arg2);
				Intent intent = new Intent(ListCourseActivity.this,CourseDetailActivity.class);
				intent.putExtra(Const.PROPERTYID, course.getId());
				startActivity(intent);
			}
		});
	}
}
